/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.controller.post;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fujitsu.nanjing.tieba.base.BaseController;
import com.fujitsu.nanjing.tieba.common.Dialog;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.exception.Resource404Exception;
import com.fujitsu.nanjing.tieba.ibator.CoreTopic;
import com.fujitsu.nanjing.tieba.service.BoardService;
import com.fujitsu.nanjing.tieba.service.TopicService;
import com.fujitsu.nanjing.tieba.struct.FileStruct;

/**
 * PostController.java
 * 
 * @author Qixiaobo-win8
 */
@Controller
@RequestMapping("/forum/boards")
public class PostController extends BaseController {
	@Resource
	private BoardService boardService;
	@Resource
	private TopicService topicService;
	@RequestMapping(value = "/{boardid}/post", method = RequestMethod.GET)
	public String show(Model model, @PathVariable String boardid)
			throws Resource404Exception {
		boardid = decrypt(boardid);
		if (boardService.findById(boardid) == null) {
			throw new Resource404Exception("该板块不存在！");
		}
		model.addAttribute("boardId", boardid);
		model.addAttribute("isTopic", "true");

		model.addAttribute("dialog", Dialog.instance().setContent(getContent()));
		return "/post/post";
	}

	@RequestMapping(value = "/{boardId}/post", method = RequestMethod.POST)
	public String create(Model model, @PathVariable String boardId,
			CoreTopic topic, String post, String subject,
			MultipartHttpServletRequest mhsRequest, HttpSession session)
			throws Resource404Exception {
		int topiIcId;
		try {
			// 其实有空的时候应该将业务代码写到domain中的
			Integer boardid = Integer.parseInt(decrypt(boardId));
			topic.setBoardid(boardid);
			topic.setTitle(filterWord(subject));
			topic.setContent(filterWord(post));
			topic.setUserid(session.getAttribute(USERID).toString());
			topic.setNickname(session.getAttribute(CURRENTUSER).toString());
			topic.setRemoteip(mhsRequest.getRemoteAddr());
			topic.setLastpostuser(session.getAttribute(USERID).toString());
			topic.setLastnickname(session.getAttribute(CURRENTUSER).toString());
			Map<String, MultipartFile> files = mhsRequest.getFileMap();
			List<FileStruct> fileStructs = initFileStruct(files, mhsRequest);
			topic.setAttaches((byte) fileStructs.size());
			if (fileStructs.size() > 0) {
				topic.setAttachicon("A");
			}
			checkPicture(topic);
			initWebRoot();
			topiIcId = topicService.insertWithAttaches(topic, fileStructs);

		} catch (Exception ex) {
			throw new Resource404Exception(ex.getMessage());
		}
		return redirect("/topics/" + encrypt(String.valueOf(topiIcId)));
	}
	private void checkPicture(CoreTopic topic) {
		if (topic.getContent().toLowerCase().contains("<img")) {
			topic.setAttachicon("I");
		}

	}

	/** 将表单域里的相关加入数据结构中 */
	public List<FileStruct> initFileStruct(Map<String, MultipartFile> files,
			MultipartHttpServletRequest request) {
		List<FileStruct> fileStructs = new ArrayList<FileStruct>();
		FileStruct fileStruct = null;
		for (Entry<String, MultipartFile> file : files.entrySet()) {
			fileStruct = new FileStruct();
			if (file.getValue() == null || file.getValue().getSize() == 0) {
				continue;
			}
			String[] args = file.getKey().split("_");
			int localId = Integer.parseInt(args[1]);
			fileStruct.setFile(file.getValue());
			int credits = Integer.parseInt(request
					.getParameter("attachcredits_" + localId));
			fileStruct.setCredits(credits);
			String title = request.getParameter("attachtitle_" + localId);
			fileStruct.setTitle(title);
			fileStruct.setLocalid(localId);
			fileStructs.add(fileStruct);
		}
		return fileStructs;

	}
	@RequestMapping("/upload")
	@ResponseBody
	public String uploadPicture(Model model,
			MultipartHttpServletRequest mhsRequest) {
		Map<String, MultipartFile> files = mhsRequest.getFileMap();
		initWebRoot();
		List<String> links = savePhoto(files);
		if (links.size() > 0) {
			return links.get(0);
		}
		return "/resource/logo.gif";

	}
	private List<String> savePhoto(Map<String, MultipartFile> files) {
		List<String> links = new ArrayList<String>();
		for (Entry<String, MultipartFile> entry : files.entrySet()) {
			MultipartFile file = entry.getValue();
			if (file.getContentType().startsWith("image")) {
				logger.info("上传图片：" + file.getOriginalFilename());
			} else {
				logger.info("上传文件：" + file.getOriginalFilename());
			}
			// 产生随机的名字
			String tempName = String.valueOf(System.nanoTime())
					+ file.getOriginalFilename().substring(
							file.getOriginalFilename().lastIndexOf("."));
			// 将文件写入upload目录下
			File dest = new File(CommonParamter.webRoot
					+ CommonParamter.uploadPath + File.separatorChar + tempName);
			links.add(CommonParamter.uploadPath + "/" + tempName);
			try {
				file.transferTo(dest);
			} catch (IllegalStateException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		}
		return links;
	}
}
